package wp.ggt.com.myapplication.utils;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.LruCache;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by KF on 2016/4/8.
 * 图片加载类
 */
public class ImagerLoader {
    private static ImagerLoader imagerLoader;
    //图片存储的核心对象
    private LruCache<String, Bitmap> mLruCache;
    //线程池
    private ExecutorService mThreadPool;
    private static final int DEAFULT_THERAD_COUNT = 1;
    //队列的调度方式
    private Type mType = Type.LIFO;
    //任务队列
    private LinkedList<Runnable> mTaskQueue;
    //后台轮询线程
    private Thread mPoolThread;
    private Handler mPoolThreadHandler;
    private Handler mUIHandler;
    //用信号量设置并行策略
    private Semaphore semaphorePoolHandler = new Semaphore(0);
    private Semaphore semaphorePoolThread;

    /**
     * 从任务队列取出一个任务
     *
     * @return
     */
    public Runnable getTask() {
        if (mType == Type.FIFO) {
            return mTaskQueue.removeFirst();
        } else {
            return mTaskQueue.removeLast();
        }
    }

    public enum Type {
        FIFO, LIFO
    }

    private ImagerLoader(int threadCount, Type type) {
        init(threadCount, type);
    }

    private void init(int threadCount, Type type) {
        semaphorePoolThread = new Semaphore(threadCount);
        //后台轮询线程
        mPoolThread = new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                mPoolThreadHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        //通过线程池取出一个任务去执行
                        mThreadPool.execute(getTask());
                        try {
                            semaphorePoolThread.acquire();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };
                semaphorePoolHandler.release();
                Looper.loop();
            }
        };
        mPoolThread.start();
        //获取应用的最大使用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheMemory = maxMemory / 8;
        mLruCache = new LruCache<String, Bitmap>(cacheMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
        };
        //创建线程池
        mThreadPool = Executors.newFixedThreadPool(threadCount);
        mTaskQueue = new LinkedList<>();
        mType = type;
    }

    public static ImagerLoader getInstance(int threadCount, Type type) {
        if (imagerLoader == null) {
            synchronized (ImagerLoader.class) {
                if (imagerLoader == null) {
                    imagerLoader = new ImagerLoader(threadCount, type);
                }
            }
        }
        return imagerLoader;
    }

    /**
     * 根据path为Imagerview设置图片
     *
     * @param path
     * @param imageView
     */

    public void loadImage(final String path, final ImageView imageView) {
        imageView.setTag(path);
        if (mUIHandler == null) {
            mUIHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    //获取得到的图片，为imagerview 设置图片
                    ImgBeanHolder imgBeanHolder = (ImgBeanHolder) msg.obj;
                    Bitmap bm = imgBeanHolder.bitmap;
                    ImageView iv = imgBeanHolder.imageView;
                    if (iv.getTag().toString().equals(imgBeanHolder.path)) {
                        iv.setImageBitmap(bm);
                    }
                }
            };
        }
        Bitmap bm = getBitmapFromLruCache(path);
        if (bm != null) {
            setBitmap(path, imageView, bm);
        } else {
            addTasks(new Runnable() {
                @Override
                public void run() {
                    //加载图片，图片压缩
                    //1.得到图片需要显示的宽高
                    ImageSize imageViewSize = getImageViewSize(imageView);
                    //2.压缩图片
                    Bitmap bm = compressBitmap(path, imageViewSize.width, imageViewSize.height);
                    //3。把图片加入缓存
                    addBitmapToLruCache(path, bm);
                    //4。设置图片
                    setBitmap(path, imageView, bm);
                    //释放信号量
                    semaphorePoolThread.release();
                }
            });
        }
    }

    private void addBitmapToLruCache(String path, Bitmap bm) {
        if (getBitmapFromLruCache(path) == null) {
            mLruCache.put(path, bm);
        }
    }


    private void setBitmap(String path, ImageView imageView, Bitmap bm) {
        Message message = Message.obtain();
        ImgBeanHolder imgBeanHolder = new ImgBeanHolder();
        imgBeanHolder.bitmap = bm;
        imgBeanHolder.imageView = imageView;
        imgBeanHolder.path = path;
        message.obj = imgBeanHolder;
        mUIHandler.sendMessage(message);
    }

    private Bitmap compressBitmap(String path, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = getSimpleSize(options, reqWidth, reqHeight);
        return BitmapFactory.decodeFile(path, options);
    }

    private int getSimpleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int simpleSize = 1;
        if (options.outHeight > reqHeight || options.outWidth > reqWidth) {
            simpleSize = Math.max(Math.round(options.outHeight * 1.0f / reqHeight), Math.round(options.outWidth * 1.0f / reqWidth));
        }
        return simpleSize;
    }

    private ImageSize getImageViewSize(ImageView imageView) {
        DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics();
        ImageSize imageSize = new ImageSize();
        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        int width = imageView.getWidth();

        if (width <= 0) {
            width = layoutParams.width;
        }
        if (width <= 0) {
            width = getImageViewFieldValue(imageView, "mMaxWidth");
        }
        if (width <= 0) {
            width = displayMetrics.widthPixels;
        }
        imageSize.width = width;

        int height = imageView.getHeight();
        if (height <= 0) {
            height = layoutParams.height;
        }
        if (height <= 0) {
            height = getImageViewFieldValue(imageView, "mMaxHeight");
        }
        if (height <= 0) {
            height = displayMetrics.heightPixels;
        }
        imageSize.height = height;
        return imageSize;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private int getImageViewFieldValue(Object o, String name) {
        int value = 0;
        try {
            Field field = o.getClass().getField(name);
            field.setAccessible(true);
            int anInt = field.getInt(o);
            if (anInt > 0 && anInt < Integer.MAX_VALUE) {
                value = anInt;
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return value;
    }

    private synchronized void addTasks(Runnable runnable) {
        mTaskQueue.add(runnable);
        try {
            if (mPoolThreadHandler == null)
                semaphorePoolHandler.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mPoolThreadHandler.sendEmptyMessage(0);
    }

    private Bitmap getBitmapFromLruCache(String path) {
        return mLruCache.get(path);
    }

    private class ImgBeanHolder {
        Bitmap bitmap;
        ImageView imageView;
        String path;
    }

    private class ImageSize {
        int width;
        int height;
    }
}
